
import pika
import json

class RabbitConn(object):
    """
    rabbitmq 连接类
    """
    def __init__(self,config_name,mode):
        self.config = config_name
        self.credentials = pika.PlainCredentials(self.config['user'], self.config['password'])
        self.connection = pika.BlockingConnection(
                pika.ConnectionParameters(
                host=self.config['host'],
                port=self.config['port'],
                credentials=self.credentials))
        self.channel = self.connection.channel()
        if mode == 'task':
            self.queue = self.config['task_queue']
            self.exchange = self.config['task_exchange']
            self.routing_key = self.config['task_routing_key']
            self.channel.queue_declare(
                queue=self.queue,
                auto_delete=True,
                durable=True)
        elif mode == 'url':
            self.queue = self.config['url_queue']
            self.exchange = self.config['url_exchange']
            self.routing_key = self.config['url_routing_key']
            self.channel.queue_declare(
                queue=self.queue,
                auto_delete=True,
                durable=True)
        else:
            print('mode选择无效')


        # self.channel.queue_bind(
        #     queue=self.queue,
        #     exchange=self.exchange,
        #     routing_key=self.routing_key)

    # async def get_data(self,func):
    #
    #     while True:
    #         method_frame, header_frame, body = self.channel.basic_get(
    #             queue=self.queue)
    #
    #         if not body:
    #             print('MQ队列暂无数据, 进程退出')
    #             break
    #         else:
    #             data = json.loads(body)
    #             await func(data)
    #             self.channel.basic_ack(delivery_tag=method_frame.delivery_tag)

    def send_data(self,data):
        self.channel.basic_publish(exchange=self.exchange,
                              routing_key=self.routing_key,
                              body=data)

        # print('send data {}'.format(data))

    def close(self):
        try:
            self.connection.close()
        except:
            pass